package com.dtz.rabbitmq.direct;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Producer {
	public static void main(String[] args) {
		// 1、创建连接工厂
				ConnectionFactory factory = new ConnectionFactory();
				
				// 2、设置连接属性
				factory.setUsername("admin");
				factory.setPassword("admin");
				factory.setHost("1.15.137.13");
				factory.setPort(5672);
				factory.setVirtualHost("/");
				
				Connection connection = null;
				Channel channel = null;
				
				try {
					// 3、获取连接
					connection = factory.newConnection("生产者");
					
					// 4、获取通道
					channel = connection.createChannel();
					
					// 5、声名队列
					String queue1 = "d-queuen4";
					channel.queueDeclare(queue1, true, false, true, null);
					String queue2 = "d-queuen5";
					channel.queueDeclare(queue2, true, false, false, null);
					
					// 6、声名交换机
					String exchange = "direct-test";
					channel.exchangeDeclare(exchange, BuiltinExchangeType.DIRECT, true);
					
					// 7、绑定队列及交换机
					channel.queueBind(queue1, exchange, "error");
					channel.queueBind(queue2, exchange, "info");
					channel.queueBind(queue2, exchange, "error");
					
					// 8、发送消息
					channel.basicPublish(exchange, "error", null, "error".getBytes());
					channel.basicPublish(exchange, "info", null, "info".getBytes());
					
					System.out.println("发送消息成功！");
					
				} catch (IOException | TimeoutException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally
				{
					// 9: 释放连接关闭通道
		            if (channel != null && channel.isOpen()) {
		                try {
		                    channel.close();
		                } catch (Exception ex) {
		                    ex.printStackTrace();
		                }
		            }
		            if (connection != null) {
		                try {
		                    connection.close();
		                } catch (Exception ex) {
		                    ex.printStackTrace();
		                }
		            }
				}
	}
}
